﻿using Demo.Interface;
using Demo.Model.Dto.BusinessUnit;
using Demo.Model.Entitys.BasicData;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo.Service.BasicData
{
    public class BusinessUnitService : IBusinessUnitService
    {
        private readonly ISqlSugarClient _db;
        public BusinessUnitService(ISqlSugarClient db)
        {
            _db = db;
        }
        public async Task<Tuple<bool, int, dynamic>> GetBusinessUnits(UnitQuer unitQuer)
        {

            var list = _db.Queryable<BusinessUnit>().
                WhereIF(unitQuer.Name != "", t => t.UnitName.Contains(unitQuer.Name) || t.UnitNameJp.Contains(unitQuer.Name)).
                WhereIF(unitQuer.Status != -1, t => t.Status == unitQuer.Status).
                WhereIF(unitQuer.Category != -1, t => t.Category == unitQuer.Category)
                .ToPageList(unitQuer.page, unitQuer.limit);

            return new(true, list.Count, list);
        }

        public async Task<Tuple<bool, string, dynamic>> PutUnit(UpBusinessUnit businessUnit)
        {
            var info = _db.Queryable<BusinessUnit>().InSingle(businessUnit.Id);
            if (info == null) return new(false, "数据已被删除", false);
            var isok = _db.Updateable<BusinessUnit>(businessUnit).ExecuteCommandHasChange();
            if (!isok) return new(isok, "修改失败", isok);
            return new(isok, "修改成功", isok);
        }
        public async Task<Tuple<bool, string, dynamic>> AddUnit(BusinessUnit businessUnit)
        {
            var isok = _db.Insertable(businessUnit).ExecuteCommandIdentityIntoEntity();
            if (!isok) return new(isok, "新增失败", isok);
            return new(isok, "新增成功", isok);
        }

        public async Task<Tuple<bool, string, dynamic>> DelUnit(int id)
        {
            bool isok = _db.Deleteable<BusinessUnit>(t => t.Id == id).ExecuteCommandHasChange();
            if (!isok) return new(isok, "删除失败", isok);
            return new(isok, "删除成功", isok);
        }

        public async Task<Tuple<bool, string>> PutStart(int id)
        {
            var info = _db.Queryable<BusinessUnit>().InSingle(id);
            if (info == null) return new(false, "数据已被删除");
            info.Status = info.Status > 0 ? 0 : 1;
            var isok = _db.Updateable(info).Where(t => t.Id == id).ExecuteCommandHasChange();
            if (!isok) return new(false, "操作失败");
            return new(false, "操作成功");
        }

        public async Task<Tuple<bool, string, dynamic>> GetBusinessUnit(int id)
        {
            var info = _db.Queryable<BusinessUnit>().InSingle(id);
            return new(true, "查询成功", info);
        }
    }
}
